package is.common.watchdog;

import is.common.interfaces.Command;
import is.common.interfaces.DeactivationNeededThread;
import is.common.util.ObjectStreamer;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;

/**
 * @author aspr0
 *         Date: 26.04.12
 *         Time: 19:26
 */
public class WatchdogClientThread extends WatchdogAbstractThread implements DeactivationNeededThread
{
    private Socket socket;
    private ObjectInputStream objectInputStream;
    private ObjectOutputStream objectOutputStream;
    private boolean watching;
    private Command connectionLostCommand;

    public WatchdogClientThread(String server, int port) throws IOException
    {
        super();
        socket = new Socket(server, port);
        /* streams should be initialized chequerwise??? conflicts */
        objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        objectInputStream = new ObjectInputStream(socket.getInputStream());
        objectStreamer = new ObjectStreamer(objectInputStream, objectOutputStream);
        watching = true;
    }

    public void setConnectionLostCommand(Command connectionLostCommand)
    {
        this.connectionLostCommand = connectionLostCommand;
    }

    @Override
    public void run()
    {
        while (watching)
        {
            try
            {
                objectStreamer.transmitObject(request);
                objectStreamer.receiveString();

                sleep(pollTimeout);
            }
            catch (SocketException e)
            {
                connectionLostCommand.execute();
            }
            catch (EOFException e)
            {
                connectionLostCommand.execute();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (ClassNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void deactivate() throws IOException
    {
        watching = false;

        objectInputStream.close();
        objectOutputStream.close();
        socket.close();
    }
}
